//
//  MailVerificationViewController.swift
//  ZhiTing
//
//  Created by zy on 2022/6/10.
//

import UIKit

class MailVerificationViewController: BaseViewController {

    var emailType = EmailCaptchaType.email_change_bind
    var captchaType = VerficationType.phone
    var newEmail = ""
    @UserDefaultWrapper(key: .mailCaptchaId) var captcha_id: String?

    private lazy var phoneCaptchaButton = CaptchaButton(frame: CGRect(x: 0, y: 0, width: 100, height: 40))
    
    private lazy var phoneCaptChaTextField = TitleTextField(keyboardType: .numberPad, title: "获取手机验证码".localizedString, placeHolder: "请输入验证码".localizedString, limitCount: 6).then {
        $0.textField.rightViewMode = .always
        $0.textField.rightView = phoneCaptchaButton
    }
    
    private lazy var mailCaptchaButton = CaptchaButton(frame: CGRect(x: 0, y: 0, width: 100, height: 40))

    private lazy var mailCaptchaTextField = TitleTextField(keyboardType: .numberPad, title: "获取邮箱验证码".localizedString, placeHolder: "请输入验证码".localizedString, limitCount: 6).then {
        $0.textField.rightViewMode = .always
        $0.textField.rightView = mailCaptchaButton
    }

    private lazy var doneButton = LoadingButton(title: "确定".localizedString)

    
    override func viewDidLoad() {
        super.viewDidLoad()
        
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if emailType == .email_change_bind {
            self.title = "更换邮箱".localizedString
        }else{
            self.title = "解绑邮箱".localizedString
        }
    }

    override func setupViews() {
        view.addSubview(phoneCaptChaTextField)
        view.addSubview(mailCaptchaTextField)
        view.addSubview(doneButton)
        
        phoneCaptchaButton.clickCallBack = { [weak self] _ in
            guard let self = self else { return }
            self.sendPhoneCaptcha()
        }
        
        phoneCaptchaButton.endCountingCallback = { [weak self] in
            self?.phoneCaptChaTextField.isUserInteractionEnabled = true
        }

        
        mailCaptchaButton.clickCallBack = { [weak self] _ in
            guard let self = self else { return }
            self.sendMailCaptcha()
        }
        
        mailCaptchaButton.endCountingCallback = { [weak self] in
            self?.mailCaptchaTextField.isUserInteractionEnabled = true
        }
        
        doneButton.clickCallBack = { [weak self] _ in
            guard let self = self else { return }
            self.doneButtonClick()
        }


    }
    
    override func setupConstraints() {
        
        phoneCaptChaTextField.snp.makeConstraints{
            $0.top.equalTo(ZTScaleValue(75) + Screen.k_nav_height)
            $0.left.equalToSuperview().offset(ZTScaleValue(30))
            $0.right.equalToSuperview().offset(-ZTScaleValue(30))
        }

        
        if captchaType == .email {
            phoneCaptChaTextField.isHidden = true
            mailCaptchaTextField.snp.makeConstraints {
                $0.top.equalTo(ZTScaleValue(75) + Screen.k_nav_height)
                $0.left.equalToSuperview().offset(ZTScaleValue(30))
                $0.right.equalToSuperview().offset(-ZTScaleValue(30))
            }
        }
        
        doneButton.snp.makeConstraints {
            $0.bottom.equalTo(-160 * Screen.screenRatio)
            $0.centerX.equalToSuperview()
            $0.left.equalToSuperview().offset(ZTScaleValue(30))
            $0.right.equalToSuperview().offset(-ZTScaleValue(30))
            $0.height.equalTo(50)
        }

        
        
        
    }
    
    override func setupSubscriptions() {
        if captchaType == .phone {
            phoneCaptChaTextField.textPublisher
                .map { $0 != "" }
                .sink { [weak self] (isEnable) in
                    guard let self = self else { return }
                    self.doneButton.setIsEnable(isEnable)
                }
                .store(in: &cancellables)
        }else{
            mailCaptchaTextField.textPublisher
                .map { $0 != "" }
                .sink { [weak self] (isEnable) in
                    guard let self = self else { return }
                    self.doneButton.setIsEnable(isEnable)
                }
                .store(in: &cancellables)
        }
    
    }

}

extension MailVerificationViewController {
    private func sendPhoneCaptcha(){
        //获取手机验证码
        ApiServiceManager.shared.getCaptcha(type: .change_email, target: nil) {[weak self] response in
            guard let self = self else {return}
            self.captcha_id = response.captcha_id
            self.showToast(string: "验证码已发送".localizedString)
            self.phoneCaptchaButton.beginCountDown()

        } failureCallback: {[weak self] code, err in
            guard let self = self else {return}
            self.showToast(string: err)
        }

        
    }
    
    private func sendMailCaptcha(){
        //获取邮箱验证码
        ApiServiceManager.shared.sendEmailCaptcha(user_id: UserManager.shared.currentUser.user_id, email: nil, type: emailType) {[weak self] response in
            guard let self = self else {return}
            self.showToast(string: "验证码已发送".localizedString)
            self.mailCaptchaButton.beginCountDown()

            self.captcha_id = response.captcha_id
        } failureCallback: {[weak self] code, err in
            guard let self = self else {return}
            self.showToast(string: err)
        }

    }
    
    
    private func doneButtonClick() {
        
        if captchaType == .email {
            if !(mailCaptchaTextField.text.count > 0) {
                self.showToast(string: "邮箱验证码不能为空")
                return
            }
        }else{
            if !(phoneCaptChaTextField.text.count > 0) {
                self.showToast(string: "手机验证码不能为空")
                return
            }
        }
        
        
        doneButton.buttonState = .waiting
        view.isUserInteractionEnabled = false
        
        //解绑或更改
        ApiServiceManager.shared.editEmail(email: nil, type: emailType, captcha: captchaType == .phone ? phoneCaptChaTextField.text : mailCaptchaTextField.text, captcha_id: captcha_id ?? "", verificationType: captchaType, new_email: emailType == .email_change_bind ? newEmail : nil, country_code: captchaType == .phone ? "86" : nil) {[weak self] response in
            guard let self = self else {return}
            
            if self.emailType == .email_change_bind {
                self.showToast(string: "更改完成")
            }else{
                self.showToast(string: "解绑完成")
                
            }
            self.doneButton.buttonState = .normal
            
            //更新用户信息
            ApiServiceManager.shared.cloudUserDetail(id: UserManager.shared.currentUser.user_id) { [weak self] (response) in
                guard let self = self else { return }
                /// 如果是云端的话 更新本地存储的用户信息
                UserManager.shared.currentUser = response.user_info
                UserCache.update(from: response.user_info)
                
                if let count = self.navigationController?.viewControllers.count,
                   count - 2 > 0,
                   var vcs = self.navigationController?.viewControllers {
                    vcs.remove(at: count - 2)
                    self.navigationController?.viewControllers = vcs
                }
                
                self.navigationController?.popViewController(animated: true)

            } failureCallback: { [weak self] (code, err) in
                guard let self = self else { return }
                self.showToast(string: err)
            }
            
            
            
            
        } failureCallback: {[weak self] code, err in
            guard let self = self else {return}
            self.showToast(string: err)
            DispatchQueue.main.async {[weak self] in
                guard let self = self else {return}
                self.doneButton.buttonState = .normal
                self.view.isUserInteractionEnabled = true
            }
        }

    }

}
